package com.smart.oauth2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

/**
 * 1. 客服端获取授权码 ----->   /oauth/authorize?
 * 2. 跳转登录界面 /login  用户输入账号 密码
 * 3  跳转获取授权码界面  点击授权 -- 授权回调/auth/callback?
 * 4  客服端通过授权码 换取令牌   /oauth/token?
 * 5  客服端返回令牌 客服端保存令牌
 * 6  客服端携带token访问资源服务器
 */

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    PasswordEncoder passwordEncoder;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder)
                .withUser("admin").password("123456").roles("admin");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginProcessingUrl("/login1");
        http.authorizeRequests()
                // 放行
                .antMatchers(
                        "/login1",
                        "/oauth/**",
                        "/back",
                        "/test")
                .permitAll()
                .anyRequest().authenticated();
        http.csrf().disable();
        http.cors().disable();
    }
}
